package client.comm.baoding.base;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

import client.comm.baoding.dialog.DialogManager;
import client.comm.baoding.utils.DailogShowUtil;
import client.comm.baoding.utils.StatusBarUtil;
import cn.pedant.SweetAlert.SweetAlertDialog;


/**
 * Created by Administrator on 2018/11/1 0001.
 */

public abstract class BaseDialogFragment extends DialogFragment implements BaseView {
    protected Context mContext;

    protected abstract void handleMsg(Message msg);

    protected abstract int getLayoutResource();

    protected abstract void onInitView();

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Dialog dialog = super.onCreateDialog(savedInstanceState);
        //设置Dialog的Window样式或风格
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        StatusBarUtil.setDialogWindowStyle(dialog.getWindow());
        dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    dismissAllowingStateLoss();
                    return true;
                }
                return false;
            }
        });
        return dialog;

    }
    //防止IllegalStateException: Can not perform this action after onSaveInstanceState
    @Override
    public void show(FragmentManager manager, String tag) {
//        super.show(manager, tag);
        try {
            Class c= Class.forName("android.support.v4.app.DialogFragment");
            Constructor con = c.getConstructor();
            Object obj = con.newInstance();
            Field dismissed = c.getDeclaredField("mDismissed");
            dismissed.setAccessible(true);
            dismissed.set(obj,false);
            Field shownByMe = c.getDeclaredField("mShownByMe");
            shownByMe.setAccessible(true);
            shownByMe.set(obj,false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        FragmentTransaction ft = manager.beginTransaction();
        ft.add(this, tag);
        ft.commitAllowingStateLoss();
    }
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (getLayoutResource() != 0) {
            return inflater.inflate(getLayoutResource(), null);
        } else {
            return super.onCreateView(inflater, container, savedInstanceState);
        }
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        onInitView();
    }

    protected Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if(!isViewIsNull()||getActivity()==null){
                return;
            }
//            if(isDetached()){
//                return;
//            }
            switch (msg.what) {

                default:
                    break;
            }
            // dismissProgressDialog();
            handleMsg(msg);
        }
    };
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
    }

    //防止fragment被销毁加载数据的时候崩溃
    private boolean isViewIsNull() {
        return  (isAdded()&& getView() != null
                && getView().getWindowToken() != null);
    }

    // //设置Dialog为全屏
    @Override
    public void onStart() {
        super.onStart();
        //获取屏幕尺寸
        DisplayMetrics dm = new DisplayMetrics();
        if (getActivity() != null) {
            getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        }
        Dialog dialog = getDialog();
        if (dialog != null) {
            Window window = dialog.getWindow();
            if (window != null) {
                //设置DialogFragment撑满屏幕
                window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
                }
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void showMessage(String msg) {
        //显示Toast提示框
        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showProgress(String msg) {
        //显示加载框
        DailogShowUtil.dialogShow(mContext);
    }

    @Override
    public void showProgress(String msg, int progress) {
        //显示加载框
        DailogShowUtil.dialogShow(mContext);
    }

    @Override
    public void hideProgress() {
        //关闭加载框
        DailogShowUtil.dialogDissmiss();
    }

    @Override
    public void showErrorMessage(String msg, String content) {
        DialogManager.showErrorDialog(mContext, msg, content, new SweetAlertDialog.OnSweetClickListener() {
            @Override
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                sweetAlertDialog.dismissWithAnimation();
            }
        });
    }

    @Override
    public void onDetach() {
        super.onDetach();
//        try {
//            Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
//            childFragmentManager.setAccessible(true);
//            childFragmentManager.set(this, null);
//
//        } catch (NoSuchFieldException e) {
//            throw new RuntimeException(e);
//        } catch (IllegalAccessException e) {
//            throw new RuntimeException(e);
//        }

    }


}
